package com.mgr.controller;

import java.util.ResourceBundle;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.mgr.service.CustomerService;

@Controller
public class ChangePasswordController {
	@Autowired
	private CustomerService customerService;
	private ResourceBundle rb = ResourceBundle
			.getBundle("com.mgr.messages.errorMessage");

	@RequestMapping(value = "change_password1", method = RequestMethod.POST)
	public ModelAndView changePass(@RequestParam("userOldPass") String oldPass,
			@RequestParam("userNewPass") String newPass,
			@RequestParam("userConfirmPass") String confirmPass,
			HttpSession session) {
		String user = (String) session.getAttribute("user");
		String msg = "";
		ModelAndView modelView = new ModelAndView("changepass.tile");
		if (user == null || user == "") {
			modelView.setViewName("login");
		} else {
			if (!customerService.compareNewPasswordAndConfirmPass(newPass,
					confirmPass)) {
				msg = rb.getString("comparePass");
			} else {
				if (!customerService.verifyPassword(Integer.parseInt(user),
						oldPass)) {
					msg = rb.getString("validatePass");
				}
			}
			if (msg.isEmpty()) {
				// save in database
				customerService.updateCustomerPass(Integer.parseInt(user),
						newPass);
				modelView.setViewName("change_password_success.tile");
			} else {
				modelView.setViewName("changepass.tile");
				modelView.addObject("message", msg);
			}
		}

		return modelView;
	}

	@RequestMapping("change_password")
	public String getChangePage() {
		return "changepass.tile";
	}

}